/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.edu.fatec.ads.dao;

import br.edu.fatec.ads.util.HibernateUtil;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Criterion;

/**
 *
 * @author Bruno Moura
 */
public abstract class HibernateDAO<T, ID extends Serializable>
    implements GenericDAO<T, ID>{

    private Class<T> persistentClass;

    public HibernateDAO(Class clazz){   persistentClass = clazz;    }

    public T get(ID id) {        
        return (T) HibernateUtil.getSession().get(persistentClass, id);
    }

    public ID save(T entity) {
        return (ID) HibernateUtil.getSession().save(entity);
    }

    public T merge(T entity) {
        return (T) HibernateUtil.getSession().merge(entity);
    }

    public void delete(T persistentObject) {
        HibernateUtil.getSession().delete(persistentObject);
    }

    public void saveOrUpdate(T transientObject) {
        HibernateUtil.getSession().saveOrUpdate(transientObject);
    }

    public void update(T transientObject) {
        HibernateUtil.getSession().update(transientObject);
    }

    public void beginTransaction(){
        HibernateUtil.beginTransaction();
    }

    public void commitTransaction(){
        HibernateUtil.commitTransaction();
    }

    public void rollbackTransaction(){
        HibernateUtil.rollbackTransaction();
    }

    public List<T> findByCriterion(List<Criterion> criterios)
        throws HibernateException{
        Criteria buscaPorCriterio = HibernateUtil.getSession().createCriteria(persistentClass);

        if(criterios != null && !criterios.isEmpty()){
            for(Criterion criterio : criterios){
                buscaPorCriterio.add(criterio);
            }
        }

        return buscaPorCriterio.list();
    }

    public void clearSession(){
        HibernateUtil.getSession().clear();
    }
}